package dfl.bysj.service.impl;

import dfl.bysj.config.RedisKey;
import dfl.bysj.entity.Academy;
import dfl.bysj.mapper.AcademyMapper;
import dfl.bysj.service.AcademyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author DFL
 * @since 2022-04-26
 */
@Slf4j
@Service
@NoArgsConstructor
public class AcademyServiceImpl extends ServiceImpl<AcademyMapper, Academy> implements AcademyService {

    private RedisTemplate redisTemplate;

    private AcademyMapper academyMapper;

    private List<Academy> academies;


    private AtomicReference<Academy> academy= new AtomicReference<>(new Academy());


    @Autowired
    public void setAcademyMapper(AcademyMapper academyMapper) {
        this.academyMapper = academyMapper;
    }

    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public Academy getAcademyByacaName(String acaName) {
        getAcademies();
        academies.stream()
                .filter(s->s.getAcaName().equals(acaName))
                .forEach(s-> academy.set(s));

        if (academy.get().getAcaId()==null){
            return null;
        }
        return academy.get();
    }

    @Override
    public Academy getAcademyById(Integer aca_Id) {
        getAcademies();
        log.info(academies.toString());
        academies.stream()
                .filter(s-> Objects.equals(s.getAcaId(), aca_Id))
                .forEach(s-> academy.set(s));
        if(academy.get().getAcaId()==null){
            return null;
        }
        return academy.get();
    }

    @Override
    public List<Academy> getAllAcademy() {
        getAcademies();
        return academies;
    }

    private void getAcademies(){
        academies= (List<Academy>) redisTemplate.opsForValue().get(RedisKey.ALL_ACADEMY);
        if (academies==null){
            updateRedisOfAcademies();
        }
    }

    private void updateRedisOfAcademies(){
        academies=list();
        redisTemplate.opsForValue().set(RedisKey.ALL_ACADEMY,academies,7, TimeUnit.DAYS);
    }
}
